<?php

namespace App\Service;

use App\Model\BookCategory;
use App\Model\ShopCategory;
use Illuminate\Support\Facades\Cache;

class CategoryService
{
    protected $bookCategory;
    protected $shopCategory;

    /**
     * 获取系统分类树
     * @return array|mixed
     */
    private function systemCategoryTree()
    {
        $data = Cache::get('systemCategoryTree');
        if (empty($data)) {
            $data = BookCategory::get()->toArray();
            $data = $this->categoryTree($data, 0);
            Cache::put('systemCategoryTree', $data, 60);
        }
        return $data;
    }

    /**
     * 分类数据递归处理
     * @param $data
     * @param $start
     * @return array
     */
    private function categoryTree($data, $start)
    {
        $tree = [];
        foreach ($data as $k => $v) {
            if ($v['parent_category_id'] == $start) {
                $v['subclass'] = $this->categoryTree($data, $v['category_id']);
                if ($v['subclass'] == null) {
                    unset($v['subclass']);
                }
                $tree[] = $v;
             //   unset($data[$k]);
            }
        }
        return $tree;
    }

    /**
     * 获取店铺分类树
     * @param $shopId
     * @return array|mixed
     */
    private function shopCategoryTree($shopId)
    {
        $data = Cache::get('shop' . $shopId . 'CategoryTree');
        if (empty($data)) {
            $data = ShopCategory::get()->toArray();
            $data = $this->categoryTree($data, 0);
            Cache::put('shop' . $shopId . 'CategoryTree', $data, 60);
        }
        return $data;
    }

    /**
     * 根据店铺id获取分类树
     * @param $shopId
     * @param $categoryType
     * @return array|mixed
     */
    public function getShopCategoryById($shopId, $categoryType)
    {
        if ($categoryType == 1) {
            $data = $this->shopCategoryTree($shopId);
        } else {
            $data = $this->systemCategoryTree();
        }
        return $data;
    }

}
